package com.itheima.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.SysUser;
import com.itheima.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName SecurityConfigUserService
 * @Description: TODO
 * @Author 郑乾
 * @Date 2020-07-02
 * @Version V1.0
 **/
public class SecurityConfigUserService implements UserDetailsService {
    @Reference
    UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = userService.findByUsername(username);
        if (sysUser == null) {
            return null;
        }
        //创建权限列表
        List<GrantedAuthority> authorityList = new ArrayList<>();
        for (Role role : sysUser.getRoles()) {
            SimpleGrantedAuthority grantedAuthority = new SimpleGrantedAuthority(role.getKeyword());
            authorityList.add(grantedAuthority);
            for (Permission permission : role.getPermissions()) {
                SimpleGrantedAuthority grantedAuthority2 = new SimpleGrantedAuthority(permission.getKeyword());
                authorityList.add(grantedAuthority2);
            }
        }
        //包装UserDetails,返回给安全框架
        User user = new User(sysUser.getUsername(), sysUser.getPassword(), authorityList);
        System.out.println("----------------------------");
        System.out.println(user.getUsername()+"...."+user);

        return user;
    }
}
